package com.lagou.edu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("")
public class LoginController {

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request,
                      HttpServletResponse response,
                      String username,
                      String password) throws Exception{
        // 封装了数据和页面信息的 ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        // 视图信息(封装跳转的页面信息) 逻辑视图名
        modelAndView.setViewName("login");
        if (username == null || password == null){
            return modelAndView;
        }
        if ("admin".equals(username)&& "admin".equals(password)){
            //登录成功，设置session，并跳转到主页
            request.getSession().setAttribute("isAuth",true);
            response.setStatus(200);
            response.sendRedirect("/index");
            return null;
        }
        response.setStatus(401);
        return modelAndView;
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request,
                              HttpServletResponse response) throws Exception{
        response.sendRedirect("/login");
    }


    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request,
                              HttpServletResponse response) throws Exception{
        // 封装了数据和页面信息的 ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
}
